import config from '@/common/config'
const install = (Vue, vm) => {
	let u = {};
	u.baseurl = null;
	u.KEY_SESSION_SOURCEPAGEURL = 'KEY_SESSION_SOURCEPAGEURL'; //进入页面的地址，H5完成登录后需要返回跳 
	u.KEY_SESSION_TOKEN = 'KEY_SESSION_TOKEN';
	u.KEY_SESSION_THIRD = 'KEY_SESSION_THIRD';
	u.KEY_SESSION_MOBILE = 'KEY_SESSION_MOBILE';
	//u._isLogined = false;
	u.openid = null;

	u.test = function() {
		console.log('testtest');
	};

	u.getIsLogined = function() {
		let that = this;

		let isLogined = false;
		let token = this._getStorageSync(this.KEY_SESSION_TOKEN);
		if (token != null && token != '') {
			isLogined = true;
		}
		return isLogined;

	}


	//计算是否登录，因为页面需要双向绑定来判定是否登录，所以无法使用方法，只能使用属 
	u.getBaseurl = function() {
			let baseurl = this._getStorageSync("csmbaseurl");
			if (baseurl == null || baseurl == '') {
				baseurl = config.baseUrl;
			}
			// H5模式下如果为传递地址,则默认为当前域名计算api地址
			//#ifdef H5
			if (window && baseurl == null || baseurl == '') {
				baseurl = window.location.protocol + "//" + window.location.host + "/api/";
			}
			//#endif
			return baseurl;
		},
		u._getStorageSync = function(key) {
			let sr = null;

			//#ifdef H5
			sr = sessionStorage.getItem(key);
			//#endif

			//#ifndef H5
			sr = uni.getStorageSync(key);
			//#endif	

			return sr;
		},
		u.setStorageSync = function(key, value) {
			//#ifdef H5
			sessionStorage.setItem(key, value);
			//#endif
			//#ifndef H5
			uni.setStorageSync(key, value);
			//#endif	
		},
		u.removeStorageSync = function(key) {
			//#ifdef H5
			sessionStorage.removeItem(key);
			//#endif
			//#ifndef H5
			uni.removeStorageSync(key);
			//#endif	
		};
	//接入页面做测试华，放在onLoad页面��?
	u.init = function(options, loginedFunc, unloginedFunc) {
		//#ifndef MP-WEIXIN
		if (options != null && (options.code == null || options.code == '')) {
			this.setStorageSync(this.KEY_SESSION_SOURCEPAGEURL, window.location.href);
		}
		//#endif
		this.initCode(options, loginedFunc, unloginedFunc);
	};
	u.initCode = function(options, loginedFunc, unloginedFunc) {

		options = options ? options : [];
		let that = this;
		
		// 先检测是否是第三方系统登录
		// ?thirdsystem=oa&mobile=17702162216&nickname=jpeanut&timestamp=1654298323&sign=fa0b6c579f99bf553902f94ea711270c
		// timestamp为一个小时有效期,sign=MD5($thirdsystem.$mobile.$nickname.$timestamp.$clogin_thirdsecretkey)
		if(options.thirdsystem!=null && options.thirdsystem!=''){
			that.unirequest("/csmwj/cloginuser/loginBythirdinfo", {
				thirdsystem:options.thirdsystem,
				mobile:options.mobile,
				nickname:options.nickname,
				timestamp:options.timestamp,
				sign:options.sign,
			}, function(res) {
				let token = res.data.token;
				let mobile = res.data.mobile;
				that.setSessionThird(token, mobile, null);
				if (loginedFunc && that.getIsLogined()) {
					loginedFunc(token, mobile, null);
				}
			});
			return;
		}
		
		
		//#ifdef H5
		if (that.isWeixin()) {
			let code = options.code;
			//console.log('code=' + code);
			if (code == null || code == '') {
				//console.log("getSessionThird token:", that.getSessionThird());
				if (that.getSessionThird() == null || that.getSessionThird() == '') {
					that.unirequest("/csmwj/cloginweixinajax/getweixinh5mobileurl", {}, function(res) {
						if(res.data.cloginwx=='Y'){
							let selfurl = encodeURIComponent(window.location.href);
							selfurl = that.getBaseurl() +
								"/csmwj/cloginweixinajax/fixspaurl?clogin_redirect_url=" +
								selfurl;
							selfurl = encodeURIComponent(selfurl);
							let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + res
								.data
								.cloginwxappid + "&redirect_uri=" + selfurl +
								"&response_type=code&scope=snsapi_base&state=12345#wechat_redirect";
							window.location = url;				
						}else{
							that._h5_login_process(loginedFunc,unloginedFunc);
						}
					});
				} else {
					//add by chensm@20220522 点击认证按钮,跳转到登录
					if (unloginedFunc && !that.getIsLogined()) {
						unloginedFunc();
					}
					if (loginedFunc && that.getIsLogined()) {
						loginedFunc(that.getSessionToken(), that.getSessionThirdMobile(), that
							.getSessionThird());
					}
				}
			} else {
				this.unirequest("/csmwj/cloginweixinajax/h5loginbycode", {
					code: code
				}, function(res) {
					let token = res.data.token;
					let mobile = res.data.mobile;
					let third = res.data.third;

					that.openid = third.openid;
					that.setSessionThird(token, mobile, third);
					if (loginedFunc && that.getIsLogined()) {
						loginedFunc(token, mobile, third);
					}
				});
			}
		} else {
			//add by chensm@20220522 点击认证按钮,跳转到登录
			// if (unloginedFunc && !that.getIsLogined()) {
			// 	unloginedFunc();
			// }
			// if (loginedFunc && that.getIsLogined()) {
			// 	loginedFunc(that.getSessionToken(), that.getSessionThirdMobile(), that.getSessionThird());
			// }
			that._h5_login_process(loginedFunc,unloginedFunc);
		}
		//#endif


		//#ifdef MP-WEIXIN
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				that.unirequest("/csmwj/cloginweixinajax/getOpenIdByWeixincode", {
					code: loginRes.code
				}, function(res) {
					let token = res.data.token;
					let mobile = res.data.mobile;
					let third = res.data.third;
					//let isopenidlogin = res.data.isopenidlogin;
					that.openid = third.openid;
					that.setSessionThird(token, mobile, third);
					//add by chensm@20220522 点击认证按钮,跳转到登录
					if (unloginedFunc && !that.getIsLogined()) {
						unloginedFunc();
					}
					if (loginedFunc && that.getIsLogined()) {
						loginedFunc(token, mobile, third);
					}
					//console.log(loginedFunc);
				});
			}
		});

		//#endif
	};
	// 判定为H5的登录逻辑
	u._h5_login_process = function(loginedFunc,unloginedFunc){
		let that = this;
		if (unloginedFunc && !that.getIsLogined()) {
			unloginedFunc();
		}
		if (loginedFunc && that.getIsLogined()) {
			loginedFunc(that.getSessionToken(), that.getSessionThirdMobile(), that.getSessionThird());
		}		
	}
	//跳转登录画面
	u.directLoginPage = function() {
		//console.log('directLoginPage');
		let that = this;
		that.unirequest("/csmwj/cloginuser/getconfiginfo", {
		}, function(res) {
			let loginurl = res.data.clogin_thirdloginurl;
			if(loginurl==null || loginurl==''){
				loginurl = '/pages/clogin/cloginform';
			}
			if(loginurl.indexOf("http")==0){
				window.location = loginurl;
			}else{
				uni.navigateTo({
					url: loginurl
				});
			}

		});
	};
	//注销
	u.logout = function() {
		this.clearSessionUserinfo();
	};
	u.setSessionThird = function(token, mobile, third) {
		let that = this;

		this.setStorageSync(this.KEY_SESSION_MOBILE, mobile ? mobile : "");
		this.setStorageSync(this.KEY_SESSION_TOKEN, token ? token : "");
		this.setStorageSync(this.KEY_SESSION_THIRD, third ? third : "");
		//that.calcLog
	};
	u.clearSessionUserinfo = function() {
		this.removeStorageSync(this.KEY_SESSION_TOKEN);
		this.removeStorageSync(this.KEY_SESSION_THIRD);
		this.removeStorageSync(this.KEY_SESSION_MOBILE);
	};
	u.getSessionToken = function() {
		let token = this._getStorageSync(this.KEY_SESSION_TOKEN);
		return token;
	};
	u.getSessionThird = function() {
		return this._getStorageSync(this.KEY_SESSION_THIRD);
	};
	u.getSessionThirdMobile = function() {
		let mobile = this._getStorageSync(this.KEY_SESSION_MOBILE);
		return mobile;
	};
	u.getSessionThirdAvatarUrl = function() {
		let userinfo = this.getSessionThird();
		return userinfo ? userinfo.avatarurl : "";
	};
	u.getSessionSourcepageurl = function() {
		//let sourcepageurl = uni._getStorageSync(this.KEY_SESSION_SOURCEPAGEURL);
		let sourcepageurl = this._getStorageSync(this.KEY_SESSION_SOURCEPAGEURL);
		return sourcepageurl;
	};
	u.unirequest = function(url, data, success, fail) {
		let that = this;
		url = this.getBaseurl() + url;

		//加上语言包，为了对口 后台 __('') 的多语言转化
		// if (true) {
		// 	let sep = "&";
		// 	if (url.indexOf("?") == -1) {
		// 		sep = "?";
		// 	}
		// 	url += sep + "lang=";

		// 	url += (vm._i18n != null && vm._i18n.locale == "en") ? "en" : "zh-cn";
		// }

		uni.request({
			url: url,
			data: data,
			method: 'POST',
			header: {
				CLang: vm.$i18n.locale,
			},
			success: (res) => {
				console.log("Request " + url, data, res.data);
				if (res.data.code == 1) {
					success(res.data);
				} else {
					if (fail) {
						fail(res.data);
					} else {
						uni.showToast({
							icon: 'none',
							title: (res.data == null) ? "Error" : vm.$t(res.data.msg)
						});
					}
				}
			},
			fail: (res) => {
				if (fail) {
					fail(res.data);
				}
			},
		});
	};
	//是否微信平台
	u.isWeixin = function() {
		let ua = navigator.userAgent.toLowerCase();
		let isWeixin = ua.indexOf('micromessenger') != -1;
		return isWeixin;
	};
	u.assertnotnull = function(fieldvalue, fieldname) {
		let that = this;
		if (fieldvalue == null || fieldvalue == "") {
			uni.showToast({
				icon: 'none',
				title: fieldname +" "+ vm.$t('clogin.msg.required')
			})
			return false;
		}
		return true;
	};

	vm.$u.clogin = u;
}

export default {
	install
}
